export default class EventBus {
    eventMap: Object;

    constructor() {
        this.eventMap = {};
    }

    subscribe(type: string | string[], cb: Function) {
        let types: string[] = []
        if (type instanceof Array) {
            types = type
        } else {
            types = [type]
        }
        for (const t of types) {
            this.eventMap[t] = this.eventMap[t] || [];
            const cbList: Function[] = this.eventMap[t];
            cbList.push(cb);
            return () => {
                cbList.splice(cbList.indexOf(cb), 1)
            }
        }
    }

    trigger(type: string, ...payload: any) {
        const cbList: Function[] = this.eventMap[type];
        if (cbList && cbList.length > 0) {
            for (const cb of cbList) {
                cb(...payload)
            }
        }
    }
}
